<?php
namespace App\Http\Controllers\Api\FlyGo;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Faker\Provider\Uuid;
use GuzzleHttp\Client;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis as Redis;
use App\Models\Wx\WxAppletCustomer;
use App\Models\Customer\Customer;
use App\Models\Customer\CustRank;

class CustomerController extends Controller
{

    /**
     * 用户登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login( Request $request )
    {

        $code = $request->input('code');
        if (empty($code)) {
            $return_data = ['code' => 10001, 'message' => '缺少code参数'];
        }

        $session_id = $request->input('session_id');
        if (empty($session_id)) {
            $session_id = str_replace('-', '', Uuid::uuid());
        }

        $user_info = $request->input('user_info');
        if (empty($user_info)) {
            $user_info['gender'] = 0;
            $user_info['nickName'] = null;
            $user_info['avatarUrl'] = null;
            $user_info['province'] = null;
            $user_info['city'] = null;
            $user_info['country'] = null;
        }

        //微信小程序主体
        $wx_applet = $request->input('wx_applet', 'maid');

        //服务端保存的会话信息
        $wx_applet_info = Redis::get('WX_APPLET_USER_' . $session_id);
        $unionid = null;
        if (!$wx_applet_info) {

            $http_data = [
                'appid' => getenv('APPLET_APPID'),
                'secret' => getenv('APPLET_SECRET'),
                'js_code' => $code,
                'grant_type' => 'authorization_code'
            ];

            //http实例
            $client = new Client();
            $response = $client->get('https://api.weixin.qq.com/sns/jscode2session?' . http_build_query($http_data));
            $code = $response->getStatusCode();
            if ($code != 200) {
                return response()->json(['code' => 10002, 'message' => '微信授权失败']);
            }

            $return_data = json_decode($response->getBody()->getContents(), true);

            if (isset($return_data['errcode'])) {
                return response()->json(['code' => 10003, 'message' => '微信授权失败']);
            }

            $wx_applet_info = [
                'openId' => $return_data['openid'],
                'session_key' => $return_data['session_key']
            ];

            if (isset($return_data['unionid'])) {
                $unionid = $return_data['unionid'];
            }

        } else {
            $wx_applet_info = json_decode($wx_applet_info, true);
        }

        //小程序粉丝信息
        $wx_applet_customer = WxAppletCustomer::select('id', 'pcustID')->where('openId', $wx_applet_info['openId'])->first();
        if (!$wx_applet_customer) {

            //根据unionid检查粉丝使用过的其他微信小程序
            //获取使用其他小程序时使用网站会员
            $pcustID = 0;
            if (empty($unionid)) {
                $temp_wx_applet = WxAppletCustomer::select('pcustID')->where('unionid', $unionid)->get()->toArray();
                if ($temp_wx_applet) {
                    foreach ($temp_wx_applet as &$t) {
                        if (!empty($t['pcustID'])) {
                            $pcustID = $t['pcustID'];
                            break;
                        }
                    }
                }
            }

            $wx_applet_customer = new WxAppletCustomer();
            $wx_applet_customer->uuid = str_replace('-', '', Uuid::uuid());
            $wx_applet_customer->timeStamp = Carbon::now();
            $wx_applet_customer->creator = 'api';
            $wx_applet_customer->createTime = Carbon::now();
            $wx_applet_customer->openId = $wx_applet_info['openId'];
            $wx_applet_customer->unionid = $unionid;
            $wx_applet_customer->pcustID = $pcustID;
            $wx_applet_customer->source = $wx_applet;
            $wx_applet_customer->nickName = $user_info['nickName'];
            $wx_applet_customer->country = $user_info['country'];
            $wx_applet_customer->province = $user_info['province'];
            $wx_applet_customer->city = $user_info['city'];
            $wx_applet_customer->sex = $user_info['gender'];
            $wx_applet_customer->head_pic = $user_info['avatarUrl'];
            $wx_applet_customer->save();
        }

        $wx_applet_info['id'] = $wx_applet_customer->id;
        $wx_applet_info['pcustID'] = $wx_applet_customer->pcustID;

        //保存设备信息
        $system_info = $request->input('system_info');
        if ($system_info) {
            $wx_applet_device = new WxAppletDevice();
            $wx_applet_device->uuid = str_replace('-', '', Uuid::uuid());
            $wx_applet_device->timeStamp = Carbon::now();
            $wx_applet_device->createTime = Carbon::now();
            $wx_applet_device->creator = 'api';
            $wx_applet_device->applet_customer_id = $wx_applet_info['id'];
            $wx_applet_device->model = $system_info['model'];
            $wx_applet_device->pixel_ratio = $system_info['pixelRatio'];
            $wx_applet_device->window_width = $system_info['windowWidth'];
            $wx_applet_device->window_height = $system_info['windowHeight'];
            $wx_applet_device->language = $system_info['language'];
            $wx_applet_device->version = $system_info['version'];
            $wx_applet_device->system = $system_info['system'];
            $wx_applet_device->platform = $system_info['platform'];
            $wx_applet_device->dbk_version = $system_info['SDKVersion'];
            $wx_applet_device->save();
        }

        //保存session
        Redis::setex('WX_APPLET_USER_' . $session_id, 604800, json_encode($wx_applet_info));

        return response()->json( ['code' => 200, 'message' => 'ok','data' => [
            'session_id' => $session_id,
            'userId' => $wx_applet_info['pcustID'],
            'openId' => $wx_applet_info['openId']
        ]] );

    }

    /**
     * 注册绑定
     * @param Request $request
     */
    public function register( Request $request)
    {

        $mobile = $request->input('mobile');
        if (empty($mobile)) {
            return response()->json(['code' => 10001, 'message' => '缺少mobile参数']);
        }

        if (!preg_match('/^1\d{10}$/', $mobile)) {
            return response()->json(['code' => 10002, 'message' => '手机号格式不正确']);
        }

        $sms_yzm = $request->input('sms_yzm');
        if (empty($sms_yzm)) {
            return response()->json(['code' => 10003, 'message' => '缺少sms_yzm参数']);
        }

        $session_id = $request->input('session_id');
        if (empty($session_id)) {
            return response()->json(['code' => 10004, 'message' => '缺少session_id参数']);
        }

        //redis中的短信验证码
        $yzm = '';
        $tmp = json_decode(Redis::get($session_id . 'sms_yzm_' . $mobile), true);
        if ($tmp) {
            $sc_timestamp = $tmp['SC_TIMESTAMP'];
            $sc_timeout = $tmp['SC_TIMEOUT'];
            if (($sc_timeout == -1 || $sc_timeout == 0) || ($sc_timeout > 0 && time() - $sc_timestamp <= $sc_timeout)) {
                $yzm = $tmp['SC_VALUE'];
            } else {
                return response()->json(['code' => 10005, 'message' => '短信验证码已过期']);
            }
        } else {
            return response()->json(['code' => 10006, 'message' => '短信验证码已过期']);
        }

        if ($yzm != md5($sms_yzm)) {
            return response()->json(['code' => 10007, 'message' => '短信验证码输入不正确']);
        }

        //检查会员主表
        $cust_master = Customer::select('pcustID')->where(['custID' => $mobile])->first();
        if (!$cust_master) {

            //获取等级信息
            $rankID = '';
            $rankName = '';
            $cust_rank = CustRank::select('rankID', 'rankName')->where('useFlg', 1)
                ->orderBy('rankID', 'ASC')
                ->first();
            if ($cust_rank) {
                $rankID = $cust_rank->rankID;
                $rankName = $cust_rank->rankName;
            }

            $pcustID = generate_seqno('seqno_customer', '', true);

            //保存会员主信息
            $cust_master = new Customer();
            $cust_master->uuid = str_replace('-', '', Uuid::uuid());
            $cust_master->timeStamp = Carbon::now();
            $cust_master->createTime = Carbon::now();
            $cust_master->creator = $mobile;
            $cust_master->custID = $mobile;
            $cust_master->pcustID = $pcustID;
            $cust_master->useFlg = 1;
            $cust_master->rankID = $rankID;
            $cust_master->rankName = $rankName;
            $cust_master->pwd = md5('ebsig_2017');

        } else {
            $pcustID = $cust_master->pcustID;
        }

        //服务端保存的会话信息
        $wx_applet_info = Redis::get('WX_APPLET_USER_' . $session_id);
        if (!$wx_applet_info) {
            return response()->json(['code' => 10008, 'message' => '会话session_id为空']);
        }
        $wx_applet_info = json_decode($wx_applet_info, true);

        $wx_applet_customer = WxAppletCustomer::where('openId', $wx_applet_info['openId'])->first();
        if ($wx_applet_customer) {

            //更新主表昵称、性别、头像
            $cust_master->sexy = $wx_applet_customer->sex;
            $cust_master->nickName = $wx_applet_customer->nickName;
            $cust_master->head_pic = $wx_applet_customer->head_pic;
            $cust_master->save();

            WxAppletCustomer::where('openId', $wx_applet_info['openId'])->update(['pcustID' => $pcustID]);
        }

        //保存session
        $wx_applet_info['pcustID'] = $pcustID;
        Redis::setex('WX_APPLET_USER_' . $session_id, 604800, json_encode($wx_applet_info));

        return response()->json([
            'code' => 200,
            'message' => 'ok',
            'data' => ['userId' => $pcustID]
        ]);
    }
}